package com.siam.package_util.util;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.siam.package_common.util.CloseableHttpClientUtil;
import com.siam.package_common.util.DateUtilsPlus;
import com.siam.package_common.util.Sha1Utils;
import com.siam.package_util.model.dto.OrderDetailPrintDto;
import com.siam.package_util.model.dto.OrderPrintDto;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 芯烨云打印机开放 API
 */
@Data
@Slf4j
@Component
@ConfigurationProperties(value = "xinyeyun")
public class XinYeYunUtilsTest {

    /**
     * 打印小票订单
     *
     * @param content 打印内容,打印内容使用 GBK 编码判断,不能超过12K
     * @param copies  打印份数，默认为 1，最大值为 5，超出范围将视为无效参数
     * @param voice   声音播放模式，0 为取消订单模式，1 为静音模式，2 为来单播放模式，3 为有用户申请退单了，默认为2 来单播放模式
     * @return
     */
    public static JSONObject print(String sn, String content, String copies, String voice, String mode) {
        JSONObject paramsObj = new JSONObject();
        paramsObj.put("content", content);
        paramsObj.put("copies", copies);
        paramsObj.put("voice", voice);
        paramsObj.put("mode", mode);
        paramsObj.put("sn", sn);
        JSONObject params = commonParams(paramsObj);

        JSONObject result_data = CloseableHttpClientUtil.sendPost("https://open.xpyun.net/api/openapi/xprinter/print", params.toJSONString());
        return jsonDataAnalysis(params, result_data);
    }
    /**
     * 公共参数设置
     * @param params
     * @return
     */
    public static JSONObject commonParams(JSONObject params) {
        JSONObject signParams = new JSONObject();

        signParams.put("user", "lmxy2025@163.com");
        signParams.put("key", "793dbe6d618947d884b58c967879c80c");
        signParams.put("timestamp", System.currentTimeMillis());

        JSONObject commonParams = new JSONObject();
        commonParams.putAll(signParams);
        //signParams.putAll(params);

        String signKey = getNotNullSignStr(signParams, "");
        commonParams.put("sign", signKey);

//        commonParams.put("debug", "1");
        commonParams.putAll(params);
        return commonParams;
    }

    /**
     * 获取签名
     * @param paramMap
     * @param secret
     * @return
     */
    public static String getNotNullSignStr(Map<String, Object> paramMap, String secret) {
        StringBuilder builder = new StringBuilder();
        Set<String> paramsSet = paramMap.keySet();
        for (String param : paramsSet) {
            Object value = paramMap.get(param);
            builder.append(value);
        }

        String encryptStr = builder + "";
        log.info("芯烨云开放API请求参数签名前拼接字符串：" + encryptStr);
        // 步骤三，MD5进行加密，转化为大写
        String sign = Sha1Utils.sha1(encryptStr);
        return sign;
    }

    public static JSONObject jsonDataAnalysis(JSONObject params, JSONObject result) {
        log.info("芯烨云开放API接口请求参数={},芯烨云开放API接口返回参数={}", params, result);
        JSONObject result_data = new JSONObject();
        if (result.getBoolean("success")) {
            JSONObject data = result.getJSONObject("data");
            if (data.getInteger("code") == 0) {
                result_data.put("success", data.getInteger("code") == 0 ? true : false);
                result_data.put("code", data.getInteger("code"));
                result_data.put("message", data.getString("msg"));
                result_data.put("data", data);
                return result_data;
            }
            result_data.put("success", false);
            result_data.put("code", data.getInteger("resCode"));
            result_data.put("message", data.getString("resMsg"));
            return result_data;
        }
        return result;
    }

    public static void main(String[] args) {
//        kitchenTotalOrderDataPrint();

//        kitchenTotalOrderDataPrintSingle();

        checkoutDataPrint();
    }

    private static void kitchenTotalOrderDataPrint() {
        //58mm的机器，一行打印 16 个汉字，32 个字母
        //80mm的机器，一行打印 24 个汉字，48 个字母
        List<JSONObject> mmList = new ArrayList<>();
        JSONObject mm = new JSONObject();
        mm.put("mm", 80);//打印机大小类型
        mm.put("mmFontSizeLen", 24);//打印机大小类型
        mm.put("mmLetterSizeLen", 48);//打印机大小类型
        mm.put("titleCheckoutSpaceNum", 14);//打印机空格长度
        mm.put("titleBackKitchenSpaceNum", 14);//打印机空格长度
        mmList.add(mm);
        int mmLetterSizeLen = mm.getInteger("mmLetterSizeLen");
        String character = "";
        for (int i = 0; i < mmLetterSizeLen; i++) {
            character = character + "-";
        }

        //门店后厨单打印
        String backKitchenMenuContent = "<C>" + character + "<BR></C>" +
//                "<RH n=\"2\"><TABLE col=\"24,24\" w=2 h=2><tr>桌号：" + orderPrintDto.getTableName() + "<td>下单人：" + orderPrintDto.getContactRealName() + "</tr></TABLE><BR>" +
                "<RH n=\"2\"><L><B>下单人：" + ("aaa") + "</B><BR>" +
                "<BOLD></BOLD><BR>" +
                "<BOLD>时间：" + ( "aaa") + "</BOLD><BR></L>" +
                "<C>" + character + "<BR>" +
                "<B>        </B><BR></C>" +
                "<L><B>备注：" + ( "aaa") + "</B><BR></L>" +
                "<BR><BR>" +
                "<C>" + character + "<BR></C></RH>" +
                "<L><TABLE col=\"22,18,8\" w=2 h=2><tr>商品名称<td>规格<td>数量</tr></TABLE>";
        JSONObject printResultData = new JSONObject();

        String backKitchenFoodListContent = "";
        String foodContent = "<TABLE col=\"22,18,8\" w=2 h=2><tr>" + ( "aaa") + "<td>" +
                ( "aaa") + "<td>" +
                ( "aaa") +
                ( "aaa") + "</tr></TABLE><BR>";
        backKitchenFoodListContent = backKitchenFoodListContent + foodContent;

        String titleContent = "<C><B>总单</B><BR></C>";
        String bottomContent = "<BR></L>" + character;
        backKitchenMenuContent = titleContent + backKitchenMenuContent + backKitchenFoodListContent + bottomContent;
        printResultData = print("74VP77LS538F249", backKitchenMenuContent, "1", "2", "1");

        //门店总氮打印
        System.out.println(printResultData);
    }



    /**
     * 打印后厨单商品
     * @param orderPrintDto
     * @param orderDetailPrintDto
     * @return
     */
    public static JSONObject kitchenTotalOrderDataPrintSingle() {
        //58mm的机器，一行打印 16 个汉字，32 个字母
        //80mm的机器，一行打印 24 个汉字，48 个字母
        List<JSONObject> mmList = new ArrayList<>();
        JSONObject mm = new JSONObject();
        mm.put("mm", 80);//打印机大小类型
        mm.put("mmFontSizeLen", 24);//打印机大小类型
        mm.put("mmLetterSizeLen", 48);//打印机大小类型
        mm.put("titleCheckoutSpaceNum", 14);//打印机空格长度
        mm.put("titleBackKitchenSpaceNum", 14);//打印机空格长度
        mmList.add(mm);
        int mmLetterSizeLen = mm.getInteger("mmLetterSizeLen");
        String character = "";
        for (int i = 0; i < mmLetterSizeLen; i++) {
            character = character + "-";
        }

        //门店后厨单打印
        String backKitchenMenuContent = "<C>" + character + "<BR></C>" +
//                "<RH n=\"2\"><TABLE col=\"24,24\" w=2 h=2><tr>桌号：" + orderPrintDto.getTableName() + "<td>下单人：" + orderPrintDto.getContactRealName() + "</tr></TABLE><BR>" +
                "<RH n=\"2\"><L><B>下单人：" + ("aaa") + "</B><BR>" +
                "<BOLD></BOLD><BR>" +
                "<BOLD>时间：" + ("aaa") + "</BOLD><BR></L>" +
                "<C>" + character + "<BR>" +
                "<B>        </B><BR></C>" +
                "<L><B>备注：" + ("aaa") + "</B><BR></L>" +
                "<BR><BR>" +
                "<C>" + character + "<BR></C></RH>" +
                "<L><TABLE col=\"22,18,8\" w=2 h=2><tr>商品名称<td>规格<td>数量</tr></TABLE>";
        JSONObject printResultData = new JSONObject();

        String foodContent = "<TABLE col=\"22,18,8\" w=2 h=2><tr>" + ("aaa") + "<td>" +
                ("aaa") + "<td>" +
                ("aaa") +
                ("aaa") + "</tr></TABLE><BR>";
        String titleContent = "<C><B>" + "aaa" + "</B><BR></C>";
        String bottomContent = "<BR></L>";
        String content = titleContent + backKitchenMenuContent + foodContent + bottomContent;
        printResultData = print("74VP77LS538F249", content, "1", "2", "1");

        //门店总氮打印
        return printResultData;
    }

    /**
     * 结账单打印
     *
     * @param orderPrintDto 订单信息
     * @param printingMenuList  订单商品信息
     */
    public static JSONObject checkoutDataPrint() {
        //58mm的机器，一行打印 16 个汉字，32 个字母
        //80mm的机器，一行打印 24 个汉字，48 个字母
        List<JSONObject> mmList = new ArrayList<>();
        JSONObject mm = new JSONObject();
        mm.put("mm", 80);//打印机大小类型
        mm.put("mmFontSizeLen", 24);//打印机大小类型
        mm.put("mmLetterSizeLen", 48);//打印机大小类型
        mm.put("titleCheckoutSpaceNum", 14);//打印机空格长度
        mm.put("titleBackKitchenSpaceNum", 14);//打印机空格长度
        mmList.add(mm);
        int mmLetterSizeLen = mm.getInteger("mmLetterSizeLen");
        String character = "";
        for (int i = 0; i < mmLetterSizeLen; i++) {
            character = character + "-";
        }
        String checkoutFoodListContent = "";

        String printTime = DateUtilsPlus.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");

        //用户结账单打印
        String checkoutMenuContent = "<C><B>" + ("aaa") + "</B><BR></C>" +
                "<C>" + character + "<BR></C>" +
                "<RH n=\"2\"><C><B>结账单<BR>" +
                "#" + ("aaa") + "</B><BR></C>" +
                "<L><BOLD>订单号：" + ("aaa") + "<BR>" +
                "商品总数：" + ("aaa") + "<BR>" +
                "下单时间：" + ("aaa") + "<BR>" +
                "结账时间：" + ("aaa") + "</BOLD><BR></L></RH>" +
                character + "<BR>" +
                "<TABLE col=\"24,14,10\" w=1 h=1><tr>商品名称<td>数量<td>小计</tr></TABLE>" +
                character + "<BR>";
        String foodContent = "<TABLE col=\"24,14,10\" w=2 h=2><tr>" +
                ("aaa") + "<td>" + "x" +
                ("aaa") + "<td>" +
                ("aaa") + "</tr></TABLE>" +
                "<L><TABLE col=\"46,2\"><tr>" +
                ("aaa") + "<td> </tr></TABLE></L> <BR>";
        checkoutFoodListContent = checkoutFoodListContent + foodContent;
        String characterContent = "结算清单";
        String characterText = character.substring(0, (mmLetterSizeLen / 2) - characterContent.length());
        String discountText = "";
        discountText = discountText + "<TABLE col=\"24,24\" w=1 h=1><tr>满减优惠<td>" + ("aaa") + "</tr></TABLE>";

        discountText = discountText + "<TABLE col=\"24,24\" w=1 h=1><tr>使用优惠券<td>" + ("aaa") + "</tr></TABLE>";

        String payTypeName = "";
        payTypeName = "<L><BOLD>支付方式：" + "aaa" + "</BOLD><BR></L>";
        checkoutMenuContent = checkoutMenuContent + checkoutFoodListContent + "<BR></L>" +
                "<TABLE col=\"24,24\" w=1 h=1><tr>配送费<td>" + ("aaa") + "</tr></TABLE>" +
                "<TABLE col=\"24,24\" w=1 h=1><tr>包装费<td>" + ("aaa") + "</tr></TABLE>" +
                discountText +
                characterText + characterContent + characterText + "<BR>" +
                "<TABLE col=\"24,24\" w=2 h=2><tr>实收金额<td>￥" + ("aaa") + "</tr></TABLE><RH n=\"2\"><BR>" +
                payTypeName +
                character + "<BR>" +
                "<L><BOLD>门店地址：" + ("aaa") + "<BR>" +
                "门店电话：" + ("aaa") + "</BOLD><BR></L>" +
                "<C><BOLD>谢谢惠顾，欢迎下次光临<BR>" +
                printTime + "</BOLD><BR></C></RH>";
        return print("74VP77LS538F249", checkoutMenuContent, "1", "2", "1");
    }
}